
import indexConfig from '@/config/index.config';

// import {
// 	toLogin,
// 	checkLogin
// } from '../libs/login';
import store from '../store';

const HEADER= {
		'content-type': 'application/json',
		//#ifdef H5
		'Form-type': navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1 ? 'wechat' : 'h5',
		//#endif
		//#ifdef MP
		'Form-type': 'routine',
		//#endif
		//#ifdef APP-PLUS
		'Form-type': 'app',
		//#endif
	}
/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}, params) {
	
	// console.log("-------------params:",params)
	let header
	let Url = indexConfig.baseUrl; /* 根域名不同 */
	header = HEADER;

	if (!noAuth) {
		//登录过期自动登录
		// if (!store.state.app.token && !checkLogin()) {
		// 	toLogin();
		// 	return Promise.reject({
		// 		msg: '未登录'
		// 	});
		// }
	}
	// if (store.state.app.token) header[TOKENNAME] = store.state.app.token;


	header["Authorization"] = uni.getStorageSync("token") ? uni.getStorageSync("token") : '';
	header["lang"] = uni.getStorageSync('locale_key') ? uni.getStorageSync('locale_key') : '';

	return new Promise((reslove, reject) => {
		console.log(Url  + url)
			console.log(data)
		uni.request({
			url: Url  + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
			console.log("res.data.code ",res.data.code );
				if (noVerify)
					reslove(res.data, res);
				else if (res.data.code == 200)
					reslove(res.data, res);
				else if ([410000, 410001, 410002, 401, 402].indexOf(res.data.code) !== -1) {
					store.commit("LOGOUT");
					toLogin();
					reject(res.data);
				} else if (res.data.code == 500) {
					console.log("11111111500");
					if (res.data.message && res.data.message.indexOf('登录信息已过期') != -1) {
						store.commit("LOGOUT");
					}
					reject(res.data.message || '系统异常');
				}
				else if (res.data.code == 400) {
					reject(res.data.message || '参数校验失败');
				} else if (res.data.code == 404) {
					reject(res.data.message || '没有找到相关数据');
				} else if (res.data.code == 403) {
					reject(res.data.message || '没有相关权限');
				} else
					reject(res.data.message || '系统错误');
			},
			fail: (msg) => {
				reject('请求失败');
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});



export default request;
